<?php

namespace plugin\webman\gateway;

use app\helper\Websocket\VoiceChat;
use app\model\User;
use Exception;
use GatewayWorker\Lib\Gateway;
use Shopwwi\WebmanAuth\Facade\JWT as JwtFace;
use support\Log;
use support\Redis;

class Events
{

    public static function onWorkerStart($worker)
    {

    }


    public static function onConnect($client_id)
    {

    }


    public static function onWebSocketConnect($client_id, $data): void
    {

        // 连接认证
        $tokenInfo = self::TokenVerify($data['get']['authentication']);
        if (empty($tokenInfo)) {
            Gateway::closeClient($client_id);
            return;
        }

        Gateway::bindUid($client_id, $tokenInfo['ulid']);
        Redis::setNx('BIQI_GAME:websocket:client_id:' . $client_id, $tokenInfo['ulid']);

        Log::info('用户上线：' . $tokenInfo['ulid'] . '，客户端：' . $client_id);

    }


    /**
     * token验证
     *
     * @param $token
     * @return false|array
     */
    protected static function TokenVerify($token): false|array
    {

        if (empty($token)) {
            return false;
        }

        try {
            $tokenInfo = JwtFace::verify($token);
        } catch (Exception) {
            return false;
        }

        if (empty($tokenInfo)) {
            return false;
        }

        if ($tokenInfo->iss !== config('plugin.shopwwi.auth.app.jwt.iss')) {
            return false;
        }
        if ($tokenInfo->guard !== 'user' || $tokenInfo->iat > time() || $tokenInfo->exp <= time()) {
            return false;
        }

        try {
            // 登录用户验证
            $user = User::query()->where('ulid', $tokenInfo->extend->ulid)->where('state', 1)->first();
            if (!$user) {
                return false;
            }
        } catch (Exception) {
            return false;
        }

        return $user->toArray();

    }


    public static function onMessage($client_id, $message): void
    {

        $messageData = json_decode($message, true);

        Log::info('客户端发送信息：', $messageData);

        if (!empty($messageData['scene'])) {
            // 语音聊天相关
            if ($messageData['scene'] === 'voice-chat') {
                VoiceChat::getInstance()->OnMessage($client_id, $messageData);
            }
        }

    }


    public static function onClose($client_id): void
    {

        Log::info('客户端' . $client_id . '断开连接');

        // 语音聊天相关
        VoiceChat::getInstance()->OnClose($client_id);

        Redis::del('BIQI_GAME:websocket:client_id:' . $client_id);

    }

}
